package dialect

import (
	"gitee.com/KotlinToGo/xorm/schema"
	"time"
)

// FormatTime format time as column type
func FormatTime(dialect IDialect, sqlTypeName string, t time.Time) (v interface{}) {
	// go-oci8 can handler time.Time. you can view the code in go-oci8/statement.go:bindValues()
	if dialect.URI().DBType == schema.Oracle {
		v = t

		return
	}

	switch sqlTypeName {
	case schema.Time:
		s := t.Format("2006-01-02 15:04:05") // time.RFC3339
		v = s[11:19]
	case schema.Date:
		v = t.Format("2006-01-02")
	case schema.DateTime, schema.TimeStamp, schema.Varchar: // !DarthPestilane! format time when sqlTypeName is schemas.Varchar.
		v = t.Format("2006-01-02 15:04:05")
	case schema.TimeStampz:
		if dialect.URI().DBType == schema.Mssql {
			v = t.Format("2006-01-02T15:04:05.9999999Z07:00")
		} else {
			v = t.Format(time.RFC3339Nano)
		}
	case schema.BigInt, schema.Int:
		v = t.Unix()
	default:
		v = t
	}
	return
}

func FormatColumnTime(dialect IDialect, defaultTimeZone *time.Location, col *schema.Column, t time.Time) (v interface{}) {
	if t.IsZero() {
		if col.Nullable {
			return nil
		}
		return ""
	}

	if col.TimeZone != nil {
		return FormatTime(dialect, col.SQLType.Name, t.In(col.TimeZone))
	}
	return FormatTime(dialect, col.SQLType.Name, t.In(defaultTimeZone))
}
